package com.changgou.seckill.timer;

import com.changgou.common.pojo.DateUtil;
import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author tu zy
 * @version 1.0
 * @date 2021/7/11 18:09
 * 定时将秒杀商品存入到Redis缓存
 */
@Component
public class SeckillGoodsPushTask {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    /**
     * 定时操作
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void loadGoodPushRedis(){
        /**
         *
         * 1.秒杀商品库存>0
         * 2.审核状态-》审核通过 status:1
         * 3.开始时间 start_time,结束时间end_time
         * end_time>=now()
         * 时间：时间菜单
         *      （1）求出整个时间菜单
         *      （2）确定每个时间菜单的区间值14-16
         *      （3）根据菜单时间的区间值求对应的秒杀商品数据
         *      （4）将对应的时间区间的秒杀商品数据存入Redis
         */


        setRedisTemplate(redisTemplate);
        //求时间菜单
        List<Date> dateMenus = DateUtil.getDateMenus();

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        //循环查询每个时间区间的秒杀商品
        for (Date dateMenu:dateMenus) {

            Date conversionByDate = DateUtil.conversionByDate(dateMenu);



            //时间的字符串格式
            String timeSpace = "SeckillGoods_" + DateUtil.date2Str(dateMenu);

            Example example = new Example(SeckillGoods.class);

            Example.Criteria criteria = example.createCriteria();

            //审核状态—》 审核通过 status:1
            criteria.andEqualTo("status","1");

            //秒杀商品库存大于0
            criteria.andGreaterThan("stockCount","0");


            //时间菜单的开始时间=<start_time && end_time<时间菜单的开始时间+2小时
            criteria.andGreaterThanOrEqualTo("startTime",conversionByDate);

            System.out.println(dateMenu);
            criteria.andLessThan("endTime",DateUtil.addDateHour(conversionByDate,2));

            //排除已经存入Redis中的seckillGoods(1)求出当前命名空间下所有的商品的ID（key） (2)
            //(2)每次查询排除掉之前存在的商品的key的数据
            Set keys = redisTemplate.boundHashOps(timeSpace).keys();

            if (keys != null && keys.size()>0){
                //排除
                criteria.andNotIn("id",keys);
            }
            //查询数据
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);

            for (SeckillGoods seckillGood:seckillGoods) {
                //存入到Redis
                redisTemplate.boundHashOps(timeSpace).put(seckillGood.getId(),seckillGood);

                //给每个商品做个队列
                redisTemplate.boundListOps("SeckillGoodsQueue"+seckillGood.getId()).leftPushAll(putAllIds(seckillGood.getStockCount(),seckillGood.getId()));
            }
            System.out.println("加油");
        }

    }

    /**
     * 获取每个商品的ID集合
     */
    public Long[] putAllIds(Integer num,Long id){
        Long[] ids = new Long[num];

        for (int i=0;i<ids.length;i++){
            ids[i]=id;
        }
        return ids;
    }





}
